// 移动端个人中心逻辑

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// Toast提示
function showToast(message, duration = 2000) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.animation = 'fadeOut 0.3s';
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

// 加载用户信息
async function loadUserInfo() {
    try {
        const response = await fetch('/api/user/info');
        const data = await response.json();

        if (data.success && data.user) {
            const user = data.user;
            document.getElementById('userName').textContent = user.username;
            document.getElementById('userEmail').textContent = user.email;
            document.getElementById('userAvatarText').textContent = user.username[0].toUpperCase();
            
            // 显示头像
            if (user.avatar) {
                const userAvatarImg = document.getElementById('userAvatarImg');
                const userAvatarText = document.getElementById('userAvatarText');
                const avatarPreview = document.getElementById('avatarPreview');
                
                // 添加时间戳防止缓存问题
                const avatarUrl = user.avatar.includes('?') ? user.avatar : user.avatar + '?t=' + new Date().getTime();
                
                if (userAvatarImg) {
                    userAvatarImg.src = avatarUrl;
                    userAvatarImg.style.display = 'block';
                }
                if (userAvatarText) {
                    userAvatarText.style.display = 'none';
                }
                if (avatarPreview) {
                    avatarPreview.src = avatarUrl;
                    avatarPreview.style.display = 'block';
                    const previewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
                    if (previewPlaceholder) previewPlaceholder.style.display = 'none';
                }
            } else {
                // 如果没有头像，确保显示默认状态
                const userAvatarImg = document.getElementById('userAvatarImg');
                const userAvatarText = document.getElementById('userAvatarText');
                
                if (userAvatarImg) {
                    userAvatarImg.style.display = 'none';
                }
                if (userAvatarText) {
                    userAvatarText.style.display = 'block';
                    userAvatarText.textContent = user.username ? user.username[0].toUpperCase() : '用';
                }
            }
            
            // 保存用户信息供编辑使用
            window.currentUser = user;
        } else {
            showToast('获取用户信息失败');
            setTimeout(() => {
                window.location.href = '/login';
            }, 2000);
        }
    } catch (error) {
        console.error('加载用户信息错误:', error);
        showToast('网络错误');
    }
}

// 加载答题统计
async function loadQuizStats() {
    try {
        const response = await fetch('/api/user/stats');
        const data = await response.json();

        if (data.success && data.stats) {
            const stats = data.stats;
            document.getElementById('totalQuizzes').textContent = stats.total_quizzes || 0;
            document.getElementById('avgScore').textContent = stats.average_score || 0;
            document.getElementById('totalScore').textContent = stats.total_score || 0;
            document.getElementById('accuracy').textContent = (stats.accuracy || 0) + '%';
        }
    } catch (error) {
        console.error('加载统计数据错误:', error);
    }
}

// 加载答题历史
async function loadQuizHistory() {
    const historyContainer = document.getElementById('quizHistory');
    
    try {
        const response = await fetch('/api/user/quiz-history');
        const data = await response.json();

        if (data.success && data.history && data.history.length > 0) {
            historyContainer.innerHTML = '';
            
            data.history.forEach(quiz => {
                const item = createHistoryItem(quiz);
                historyContainer.appendChild(item);
            });
        } else {
            historyContainer.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">📝</div>
                    <div class="empty-text">还没有答题记录</div>
                    <div class="empty-hint">快去开始第一次答题吧！</div>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载答题历史错误:', error);
        historyContainer.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">❌</div>
                <div class="empty-text">加载失败</div>
            </div>
        `;
    }
}

// 创建历史记录项
function createHistoryItem(quiz) {
    const div = document.createElement('div');
    div.className = 'history-item';
    
    const date = new Date(quiz.created_at).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    div.innerHTML = `
        <div class="history-header">
            <span class="history-date">${date}</span>
            <span class="history-score">${quiz.score}分</span>
        </div>
        <div class="history-details">
            <div class="detail-item-inline correct">
                <span class="detail-value">${quiz.correct_count}</span>
                <span class="detail-label">答对</span>
            </div>
            <div class="detail-item-inline wrong">
                <span class="detail-value">${quiz.wrong_count}</span>
                <span class="detail-label">答错</span>
            </div>
            <div class="detail-item-inline">
                <span class="detail-value">${formatTime(quiz.time_elapsed)}</span>
                <span class="detail-label">用时</span>
            </div>
        </div>
        <div class="history-actions">
            <button class="btn btn-primary btn-small" onclick="viewQuizDetail(${quiz.id})">
                查看详情
            </button>
        </div>
    `;
    
    return div;
}

// 查看答题详情
async function viewQuizDetail(quizId) {
    const modal = document.getElementById('detailModal');
    const content = document.getElementById('detailContent');
    
    lockBodyScroll();
    modal.style.display = 'flex';
    content.innerHTML = `
        <div class="loading">
            <div class="spinner"></div>
            <span>加载中...</span>
        </div>
    `;
    
    try {
        const response = await fetch(`/api/quiz/detail/${quizId}`);
        const data = await response.json();
        
        if (data.success && data.answers) {
            displayQuizDetail(data.answers, data.quiz_info);
        } else {
            content.innerHTML = `
                <div class="empty-state">
                    <div class="empty-text">暂无详细记录</div>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载答题详情错误:', error);
        content.innerHTML = `
            <div class="empty-state">
                <div class="empty-text">加载失败</div>
            </div>
        `;
    }
}

// 显示答题详情
function displayQuizDetail(answers, quizInfo) {
    const content = document.getElementById('detailContent');
    
    const labels = ['A', 'B', 'C', 'D'];
    
    let html = '';
    
    // 概览信息
    if (quizInfo) {
        html += `
            <div class="detail-overview">
                <div class="detail-stats">
                    <div class="detail-stat">
                        <span class="detail-stat-value">${quizInfo.score}</span>
                        <span class="detail-stat-label">总分</span>
                    </div>
                    <div class="detail-stat">
                        <span class="detail-stat-value">${quizInfo.correct_count}</span>
                        <span class="detail-stat-label">答对</span>
                    </div>
                    <div class="detail-stat">
                        <span class="detail-stat-value">${quizInfo.wrong_count}</span>
                        <span class="detail-stat-label">答错</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    html += '<div class="questions-detail-list">';
    
    answers.forEach((answer, index) => {
        const isCorrect = answer.is_correct;
        const statusClass = isCorrect ? 'correct' : 'wrong';
        const statusText = isCorrect ? '✓ 答对了' : '✗ 答错了';
        
        html += `
            <div class="question-detail-item ${statusClass}">
                <div class="question-detail-header">
                    <span class="question-number">第 ${index + 1} 题</span>
                    <span class="question-status ${statusClass}">${statusText}</span>
                </div>
                <div class="question-text">${renderMarkdown(answer.question_title)}</div>
        `;
        
        // 选项
        html += '<div class="question-options">';
        const options = [answer.option_a, answer.option_b, answer.option_c, answer.option_d];
        options.forEach((option, optIndex) => {
            const optLabel = labels[optIndex];
            const isUserAnswer = answer.user_answer === optLabel;
            const isCorrectAnswer = answer.correct_answer === optLabel;
            
            let optionClass = 'question-option';
            if (isUserAnswer && !isCorrect) {
                optionClass += ' user-selected wrong-option';
            } else if (isUserAnswer) {
                optionClass += ' user-selected';
            }
            if (isCorrectAnswer) {
                optionClass += ' correct-option';
            }
            
            html += `
                <div class="${optionClass}">
                    <div class="option-label-small">${optLabel}</div>
                    <div class="option-text-small">${renderMarkdown(option)}</div>
                </div>
            `;
        });
        html += '</div>';
        
        // 答案信息
        html += `
            <div class="answer-info">
                <div class="answer-item">
                    <span class="answer-label">你的答案：</span>
                    <span class="answer-value">${answer.user_answer || '未作答'}</span>
                </div>
                <div class="answer-item">
                    <span class="answer-label">正确答案：</span>
                    <span class="answer-value">${answer.correct_answer}</span>
                </div>
            </div>
        `;
        
        // 解析
        if (answer.explanation) {
            html += `
                <div class="question-explanation">
                    <div class="explanation-title">💡 答案解析</div>
                    <div class="explanation-content">${renderMarkdown(answer.explanation)}</div>
                </div>
            `;
        }
        
        html += '</div>';
    });
    
    html += '</div>';
    
    content.innerHTML = html;
    
    // 渲染数学公式
    setTimeout(() => {
        renderMath(content);
    }, 100);
}

// 关闭详情模态框
function closeDetailModal() {
    document.getElementById('detailModal').style.display = 'none';
    unlockBodyScroll();
}

// 打开编辑模态框
document.getElementById('editBtn').addEventListener('click', () => {
    if (window.currentUser) {
        document.getElementById('editUsername').value = window.currentUser.username;
        document.getElementById('editEmail').value = window.currentUser.email;
        
        // 设置当前头像预览
        const avatarPreview = document.getElementById('avatarPreview');
        const avatarPreviewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
        
        if (window.currentUser.avatar) {
            const avatarUrl = window.currentUser.avatar.includes('?') ? 
                window.currentUser.avatar : 
                window.currentUser.avatar + '?t=' + new Date().getTime();
            
            if (avatarPreview) {
                avatarPreview.src = avatarUrl;
                avatarPreview.style.display = 'block';
            }
            if (avatarPreviewPlaceholder) {
                avatarPreviewPlaceholder.style.display = 'none';
            }
        } else {
            if (avatarPreview) {
                avatarPreview.style.display = 'none';
            }
            if (avatarPreviewPlaceholder) {
                avatarPreviewPlaceholder.style.display = 'block';
            }
        }
        
        lockBodyScroll();
        document.getElementById('editModal').style.display = 'flex';
    }
});

// 关闭编辑模态框
function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
    unlockBodyScroll();
}

// 提交编辑表单
document.getElementById('editForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const username = document.getElementById('editUsername').value.trim();
    const email = document.getElementById('editEmail').value.trim();
    
    if (!username || !email) {
        showToast('请填写所有字段');
        return;
    }
    
    try {
        const response = await fetch('/api/user/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, email })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast('更新成功');
            closeEditModal();
            loadUserInfo();
        } else {
            showToast(data.message || '更新失败');
        }
    } catch (error) {
        console.error('更新用户信息错误:', error);
        showToast('网络错误');
    }
});

// 退出登录
document.getElementById('logoutBtn').addEventListener('click', async () => {
    if (confirm('确定要退出登录吗？')) {
        try {
            const response = await fetch('/api/logout', {
                method: 'POST'
            });
            
            const data = await response.json();
            
            if (data.success) {
                showToast('已退出登录');
                setTimeout(() => {
                    window.location.href = '/';
                }, 1000);
            }
        } catch (error) {
            console.error('退出登录错误:', error);
            showToast('退出失败');
        }
    }
});

// 格式化时间
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 设置当前导航项为激活状态
function setActiveNav() {
    const path = window.location.pathname;
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('href') === path) {
            item.classList.add('active');
        }
    });
}

// 头像上传功能
function setupAvatarUpload() {
    console.log('setupAvatarUpload 被调用');
    const avatarInput = document.getElementById('avatarInput');
    const avatarPreview = document.getElementById('avatarPreview');
    const avatarPreviewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
    const uploadAvatarForm = document.getElementById('uploadAvatarForm');
    const avatarError = document.getElementById('avatarError');

    console.log('找到的元素:', {
        avatarInput: !!avatarInput,
        avatarPreview: !!avatarPreview,
        avatarPreviewPlaceholder: !!avatarPreviewPlaceholder,
        uploadAvatarForm: !!uploadAvatarForm,
        avatarError: !!avatarError
    });

    if (!avatarInput || !uploadAvatarForm) {
        console.error('关键元素未找到，头像上传功能无法初始化');
        return;
    }

    // 预览头像
    avatarInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件大小 (5MB)
            if (file.size > 5 * 1024 * 1024) {
                avatarError.textContent = '文件大小不能超过5MB';
                showToast('文件大小不能超过5MB');
                return;
            }
            
            // 检查文件类型
            const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                avatarError.textContent = '只支持 PNG、JPG、GIF、WEBP 格式';
                showToast('只支持图片格式');
                return;
            }
            
            // 预览图片
            const reader = new FileReader();
            reader.onload = function(event) {
                if (avatarPreview) {
                    avatarPreview.src = event.target.result;
                    avatarPreview.style.display = 'block';
                }
                if (avatarPreviewPlaceholder) {
                    avatarPreviewPlaceholder.style.display = 'none';
                }
            };
            reader.readAsDataURL(file);
            avatarError.textContent = '';
        }
    });

    // 上传头像
    uploadAvatarForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        console.log('头像上传表单提交');
        
        const file = avatarInput.files[0];
        if (!file) {
            console.error('没有选择文件');
            avatarError.textContent = '请选择头像图片';
            showToast('请选择头像图片');
            return;
        }
        
        console.log('选择的文件:', file.name, '大小:', file.size, '类型:', file.type);
        
        const formData = new FormData();
        formData.append('avatar', file);
        
        const uploadBtn = document.getElementById('uploadAvatarBtn');
        uploadBtn.disabled = true;
        uploadBtn.textContent = '上传中...';
        
        try {
            console.log('开始上传头像到 /api/user/upload-avatar');
            const response = await fetch('/api/user/upload-avatar', {
                method: 'POST',
                body: formData
            });
            
            console.log('服务器响应状态:', response.status);
            const data = await response.json();
            console.log('服务器响应数据:', data);
            
            if (data.success) {
                showToast('头像上传成功！');
                // 更新页面上的头像
                const userAvatarImg = document.getElementById('userAvatarImg');
                const userAvatarText = document.getElementById('userAvatarText');
                const avatarPreview = document.getElementById('avatarPreview');
                const avatarPreviewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
                
                // 添加时间戳防止浏览器缓存
                const avatarUrlWithTimestamp = data.avatar_url + '?t=' + new Date().getTime();
                
                if (userAvatarImg) {
                    userAvatarImg.src = avatarUrlWithTimestamp;
                    userAvatarImg.style.display = 'block';
                }
                if (userAvatarText) {
                    userAvatarText.style.display = 'none';
                }
                // 同时更新模态框中的头像预览
                if (avatarPreview) {
                    avatarPreview.src = avatarUrlWithTimestamp;
                    avatarPreview.style.display = 'block';
                }
                if (avatarPreviewPlaceholder) {
                    avatarPreviewPlaceholder.style.display = 'none';
                }
                avatarError.textContent = '';
                
                // 更新全局用户信息
                if (window.currentUser) {
                    window.currentUser.avatar = data.avatar_url;
                }
                
                // 关闭编辑模态框
                setTimeout(() => {
                    closeEditModal();
                }, 1000);
            } else {
                avatarError.textContent = data.message || '上传失败';
                showToast(data.message || '上传失败');
            }
        } catch (error) {
            console.error('上传头像错误:', error);
            avatarError.textContent = '上传失败，请重试';
            showToast('上传失败，请重试');
        } finally {
            uploadBtn.disabled = false;
            uploadBtn.textContent = '上传头像';
        }
    });
}

// 加载成就数据
async function loadAchievements() {
    try {
        const response = await fetch('/api/user/achievements');
        const data = await response.json();

        if (data.success) {
            displayLevelInfo(data.level);
            displayAchievementsPreview(data.achievements);
        } else {
            console.error('获取成就失败:', data.message);
        }
    } catch (error) {
        console.error('加载成就错误:', error);
    }
}

// 显示等级信息
function displayLevelInfo(level) {
    const levelElement = document.getElementById('userLevel');
    const expFillElement = document.getElementById('expFill');
    const expTextElement = document.getElementById('expText');

    if (levelElement) {
        levelElement.textContent = `Lv.${level.level}`;
    }

    if (expFillElement && expTextElement) {
        const currentExp = level.experience;
        const expForNextLevel = level.level * 100;
        const percentage = (currentExp / expForNextLevel) * 100;

        expFillElement.style.width = `${Math.min(percentage, 100)}%`;
        expTextElement.textContent = `${currentExp}/${expForNextLevel}`;
    }
}

// 显示成就预览
function displayAchievementsPreview(achievements) {
    const previewElement = document.getElementById('achievementsPreview');
    if (!previewElement) return;

    const unlockedCount = achievements.unlocked.length;
    const totalCount = achievements.unlocked.length + achievements.locked.length;

    // 显示最近解锁的3个成就
    const recentAchievements = achievements.unlocked.slice(0, 3);

    let html = '';
    if (recentAchievements.length > 0) {
        recentAchievements.forEach(achievement => {
            html += `
                <div class="achievement-preview-item">
                    <div class="achievement-icon">${achievement.icon}</div>
                    <div class="achievement-info">
                        <div class="achievement-name">${achievement.name}</div>
                        <div class="achievement-rarity ${achievement.rarity}">${achievement.rarity}</div>
                    </div>
                </div>
            `;
        });
    } else {
        html = `
            <div class="empty-achievements">
                <div class="empty-icon">🏆</div>
                <div class="empty-title">暂无成就</div>
                <div class="empty-desc">完成答题挑战，解锁专属成就徽章！</div>
                <div class="achievement-hints">
                    <div class="hint-item">
                        <span class="hint-icon">🎯</span>
                        <span class="hint-text">答对10题解锁「初出茅庐」</span>
                    </div>
                    <div class="hint-item">
                        <span class="hint-icon">⭐</span>
                        <span class="hint-text">连续答题5天解锁「坚持不懈」</span>
                    </div>
                    <div class="hint-item">
                        <span class="hint-icon">🔥</span>
                        <span class="hint-text">获得满分解锁「完美答卷」</span>
                    </div>
                </div>
            </div>
        `;
    }

    html += `<div class="achievement-count">${unlockedCount}/${totalCount} 已解锁</div>`;
    previewElement.innerHTML = html;
}

// 显示所有成就
function displayAllAchievements(achievements) {
    const listElement = document.getElementById('allAchievementsList');
    if (!listElement) return;

    let html = '';

    // 已解锁成就
    if (achievements.unlocked.length > 0) {
        html += '<h4>已解锁成就</h4>';
        achievements.unlocked.forEach(achievement => {
            html += `
                <div class="achievement-item unlocked">
                    <div class="achievement-icon">${achievement.icon}</div>
                    <div class="achievement-content">
                        <h5 class="achievement-name">${achievement.name}</h5>
                        <p class="achievement-desc">${achievement.description}</p>
                        <div class="achievement-meta">
                            <span class="achievement-rarity ${achievement.rarity}">${achievement.rarity}</span>
                            <span class="achievement-date">${achievement.unlocked_at}</span>
                        </div>
                    </div>
                </div>
            `;
        });
    }

    // 未解锁成就
    if (achievements.locked.length > 0) {
        html += '<h4>未解锁成就</h4>';
        achievements.locked.forEach(achievement => {
            html += `
                <div class="achievement-item locked">
                    <div class="achievement-icon locked">${achievement.icon}</div>
                    <div class="achievement-content">
                        <h5 class="achievement-name">${achievement.name}</h5>
                        <p class="achievement-desc">${achievement.description}</p>
                        <div class="achievement-meta">
                            <span class="achievement-rarity ${achievement.rarity}">${achievement.rarity}</span>
                        </div>
                    </div>
                </div>
            `;
        });
    }

    listElement.innerHTML = html;
}

// 加载学习目标
async function loadLearningGoals() {
    try {
        const response = await fetch('/api/user/learning-goals');
        const data = await response.json();

        if (data.success) {
            displayGoalsPreview(data.goals);
        } else {
            console.error('获取学习目标失败:', data.message);
        }
    } catch (error) {
        console.error('加载学习目标错误:', error);
    }
}

// 显示目标预览
function displayGoalsPreview(goals) {
    const dailyGoal = goals.find(g => g.goal_type === 'daily');
    const weeklyGoal = goals.find(g => g.goal_type === 'weekly');

    // 每日目标
    const dailyItem = document.querySelector('.goal-item[data-goal-type="daily"]');
    if (dailyItem) {
        updateGoalItem(dailyItem, dailyGoal, 'daily');
    }

    // 每周目标
    const weeklyItem = document.querySelector('.goal-item[data-goal-type="weekly"]');
    if (weeklyItem) {
        updateGoalItem(weeklyItem, weeklyGoal, 'weekly');
    }
}

// 更新目标卡片
function updateGoalItem(itemElement, goal, goalType) {
    const statusElement = itemElement.querySelector('.goal-status');
    const descriptionElement = itemElement.querySelector('.goal-description');
    const progressSection = itemElement.querySelector('.goal-progress-section');
    const detailSection = itemElement.querySelector('.goal-detail');
    
    if (!goal) {
        // 未设置目标
        statusElement.setAttribute('data-status', 'not-set');
        statusElement.textContent = '未设置';
        
        const typeNames = {
            'daily': '今天',
            'weekly': '本周'
        };
        descriptionElement.textContent = `${typeNames[goalType]}还没有设置学习目标，点击下方按钮开始设置吧！`;
        
        detailSection.style.display = 'block';
        progressSection.style.display = 'none';
        return;
    }
    
    // 已设置目标，显示进度
    // 这里使用随机数模拟当前进度，实际应该从后端获取真实进度
    const currentProgress = Math.floor(Math.random() * (goal.target_quizzes + 1));
    const percentage = goal.target_quizzes > 0 ? Math.min((currentProgress / goal.target_quizzes) * 100, 100) : 0;
    
    // 更新状态
    if (currentProgress >= goal.target_quizzes) {
        statusElement.setAttribute('data-status', 'completed');
        statusElement.textContent = '已完成 ✓';
    } else {
        statusElement.setAttribute('data-status', 'in-progress');
        statusElement.textContent = '进行中';
    }
    
    // 更新描述
    let goalDesc = `目标：完成 ${goal.target_quizzes} 题`;
    if (goal.target_score > 0) {
        goalDesc += `，平均 ${goal.target_score} 分`;
    }
    if (goal.target_accuracy > 0) {
        goalDesc += `，正确率 ${goal.target_accuracy}%`;
    }
    descriptionElement.textContent = goalDesc;
    
    // 更新进度
    const progressText = itemElement.querySelector('.goal-progress-text');
    const progressFill = itemElement.querySelector('.progress-fill');
    
    if (progressText && progressFill) {
        progressText.textContent = `${currentProgress}/${goal.target_quizzes} 题`;
        progressFill.style.width = `${percentage}%`;
    }
    
    detailSection.style.display = 'block';
    progressSection.style.display = 'block';
}

// 显示全部成就模态框
function showAllAchievements() {
    console.log('showAllAchievements 被调用');
    const modal = document.getElementById('achievementsModal');
    console.log('找到模态框:', modal);
    if (modal) {
        lockBodyScroll();
        modal.style.display = 'flex';
        // 重新加载成就数据
        loadAchievements().then(() => {
            // 获取完整的成就数据来显示
            fetch('/api/user/achievements')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayAllAchievements(data.achievements);
                    }
                });
        });
    }
}

// 关闭成就模态框
function closeAchievementsModal() {
    const modal = document.getElementById('achievementsModal');
    if (modal) {
        modal.style.display = 'none';
        unlockBodyScroll();
    }
}

// 显示目标设置模态框
function showGoalSettings() {
    console.log('showGoalSettings 被调用');
    const modal = document.getElementById('goalSettingsModal');
    console.log('找到模态框:', modal);
    if (modal) {
        lockBodyScroll();
        modal.style.display = 'flex';
        console.log('目标设置模态框应该已显示');
    } else {
        console.error('未找到 goalSettingsModal 元素');
    }
}

// 关闭目标设置模态框
function closeGoalSettingsModal() {
    const modal = document.getElementById('goalSettingsModal');
    if (modal) {
        modal.style.display = 'none';
        unlockBodyScroll();
    }
}

// 保存移动端学习目标
async function saveMobileLearningGoal() {
    const goalType = document.getElementById('goalTypeSelect').value;
    const targetQuizzes = document.getElementById('mobileTargetQuizzes').value;
    const targetScore = document.getElementById('mobileTargetScore').value;
    const targetAccuracy = document.getElementById('mobileTargetAccuracy').value;

    // 表单验证
    if (!targetQuizzes || parseInt(targetQuizzes) <= 0) {
        showToast('请输入有效的目标答题次数（必须大于0）');
        return;
    }

    // 选填项验证
    if (targetScore && (parseInt(targetScore) < 0 || parseInt(targetScore) > 100)) {
        showToast('目标得分应在 0-100 之间');
        return;
    }

    if (targetAccuracy && (parseInt(targetAccuracy) < 0 || parseInt(targetAccuracy) > 100)) {
        showToast('目标正确率应在 0-100 之间');
        return;
    }

    // 目标类型说明
    const goalTypeNames = {
        'daily': '每日',
        'weekly': '每周',
        'monthly': '每月'
    };

    try {
        const response = await fetch('/api/user/learning-goals', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                goal_type: goalType,
                target_quizzes: parseInt(targetQuizzes) || 0,
                target_score: parseInt(targetScore) || 0,
                target_accuracy: parseInt(targetAccuracy) || 0
            })
        });

        const data = await response.json();

        if (data.success) {
            showToast(`${goalTypeNames[goalType]}目标设置成功：答题 ${targetQuizzes} 次`);
            closeGoalSettingsModal();
            loadLearningGoals(); // 重新加载目标
        } else {
            showToast(data.message || '设置失败');
        }
    } catch (error) {
        console.error('保存学习目标错误:', error);
        showToast('网络错误，请稍后重试');
    }
}

// 设置目标模态框
function setupGoalModal() {
    const form = document.getElementById('mobileGoalForm');
    if (form) {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            await saveMobileLearningGoal();
        });
    }
}

// 模态框控制函数
function lockBodyScroll() {
    const scrollY = window.scrollY;
    document.body.style.position = 'fixed';
    document.body.style.top = `-${scrollY}px`;
    document.body.style.width = '100%';
    document.body.classList.add('modal-open');
}

function unlockBodyScroll() {
    const scrollY = document.body.style.top;
    document.body.style.position = '';
    document.body.style.top = '';
    document.body.style.width = '';
    document.body.classList.remove('modal-open');
    window.scrollTo(0, parseInt(scrollY || '0') * -1);
}

// 偏好设置相关函数
function showPreferencesModal() {
    console.log('showPreferencesModal 被调用');
    const modal = document.getElementById('preferencesModal');
    console.log('找到模态框:', modal);
    if (modal) {
        lockBodyScroll();
        loadUserPreferences();
        modal.style.display = 'flex'; // 使用 flex 而不是 block
        console.log('模态框应该已显示');
    } else {
        console.error('未找到 preferencesModal 元素');
    }
}

function closePreferencesModal() {
    const modal = document.getElementById('preferencesModal');
    if (modal) {
        modal.style.display = 'none';
        unlockBodyScroll();
    }
}

async function loadUserPreferences() {
    try {
        const response = await fetch('/api/user/preferences');
        const data = await response.json();

        if (data.success && data.preferences) {
            const prefs = data.preferences;
            document.getElementById('themeSelect').value = prefs.theme || 'light';
            document.getElementById('notificationsEnabled').checked = prefs.notifications_enabled || false;
            document.getElementById('reminderEnabled').checked = prefs.reminder_enabled || false;
            document.getElementById('reminderTime').value = prefs.reminder_time || '09:00';
            document.getElementById('languageSelect').value = prefs.language || 'zh-CN';
            
            // 显示/隐藏提醒时间设置
            toggleReminderTimeGroup();
        }
    } catch (error) {
        console.error('加载用户偏好失败:', error);
    }
}

function toggleReminderTimeGroup() {
    const reminderEnabled = document.getElementById('reminderEnabled').checked;
    const reminderTimeGroup = document.getElementById('reminderTimeGroup');
    if (reminderTimeGroup) {
        reminderTimeGroup.style.display = reminderEnabled ? 'block' : 'none';
    }
}

async function saveUserPreferences() {
    const preferences = {
        theme: document.getElementById('themeSelect').value,
        notifications_enabled: document.getElementById('notificationsEnabled').checked,
        reminder_enabled: document.getElementById('reminderEnabled').checked,
        reminder_time: document.getElementById('reminderTime').value,
        language: document.getElementById('languageSelect').value
    };

    try {
        const response = await fetch('/api/user/preferences', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(preferences)
        });

        const data = await response.json();

        if (data.success) {
            showToast('设置保存成功');
            closePreferencesModal();
        } else {
            showToast(data.message || '保存失败');
        }
    } catch (error) {
        console.error('保存用户偏好失败:', error);
        showToast('保存失败');
    }
}

// 数据导出相关函数
function showDataExportModal() {
    console.log('showDataExportModal 被调用');
    const modal = document.getElementById('dataExportModal');
    console.log('找到模态框:', modal);
    if (modal) {
        lockBodyScroll();
        modal.style.display = 'flex';
        console.log('数据导出模态框应该已显示');
    } else {
        console.error('未找到 dataExportModal 元素');
    }
}

function closeDataExportModal() {
    const modal = document.getElementById('dataExportModal');
    if (modal) {
        modal.style.display = 'none';
        unlockBodyScroll();
    }
}

async function exportQuizHistory() {
    try {
        const response = await fetch('/api/user/quiz-history');
        const data = await response.json();

        if (data.success && data.history) {
            const csvContent = generateQuizHistoryCSV(data.history);
            downloadCSV(csvContent, 'quiz_history.csv');
            showToast('答题记录导出成功');
        } else {
            showToast('导出失败：无数据');
        }
    } catch (error) {
        console.error('导出答题记录失败:', error);
        showToast('导出失败');
    }
}

async function exportAchievements() {
    try {
        const response = await fetch('/api/user/achievements');
        const data = await response.json();

        if (data.success && data.achievements) {
            const csvContent = generateAchievementsCSV(data.achievements);
            downloadCSV(csvContent, 'achievements.csv');
            showToast('成就数据导出成功');
        } else {
            showToast('导出失败：无数据');
        }
    } catch (error) {
        console.error('导出成就数据失败:', error);
        showToast('导出失败');
    }
}

async function exportStatistics() {
    try {
        const response = await fetch('/api/user/stats');
        const data = await response.json();

        if (data.success && data.stats) {
            const csvContent = generateStatisticsCSV(data.stats);
            downloadCSV(csvContent, 'statistics.csv');
            showToast('统计数据导出成功');
        } else {
            showToast('导出失败：无数据');
        }
    } catch (error) {
        console.error('导出统计数据失败:', error);
        showToast('导出失败');
    }
}

function generateQuizHistoryCSV(history) {
    const headers = ['日期', '得分', '答对题数', '答错题数', '用时(秒)'];
    const rows = history.map(quiz => [
        new Date(quiz.created_at).toLocaleString('zh-CN'),
        quiz.score,
        quiz.correct_count,
        quiz.wrong_count,
        quiz.time_elapsed
    ]);
    
    return [headers, ...rows].map(row => row.join(',')).join('\n');
}

function generateAchievementsCSV(achievements) {
    const headers = ['成就名称', '描述', '稀有度', '解锁时间'];
    const rows = achievements.unlocked.map(achievement => [
        achievement.name,
        achievement.description,
        achievement.rarity,
        achievement.unlocked_at || ''
    ]);
    
    return [headers, ...rows].map(row => row.join(',')).join('\n');
}

function generateStatisticsCSV(stats) {
    const headers = ['指标', '数值'];
    const rows = [
        ['总答题次数', stats.total_quizzes || 0],
        ['平均分', stats.average_score || 0],
        ['总得分', stats.total_score || 0],
        ['正确率(%)', stats.accuracy || 0]
    ];
    
    return [headers, ...rows].map(row => row.join(',')).join('\n');
}

function downloadCSV(content, filename) {
    const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 关于应用相关函数
function showAboutModal() {
    console.log('showAboutModal 被调用');
    const modal = document.getElementById('aboutModal');
    console.log('找到模态框:', modal);
    if (modal) {
        lockBodyScroll();
        modal.style.display = 'flex';
        console.log('关于应用模态框应该已显示');
    } else {
        console.error('未找到 aboutModal 元素');
    }
}

function closeAboutModal() {
    const modal = document.getElementById('aboutModal');
    if (modal) {
        modal.style.display = 'none';
        unlockBodyScroll();
    }
}

// 设置偏好表单提交
function setupPreferencesForm() {
    const form = document.getElementById('preferencesForm');
    const reminderEnabledCheckbox = document.getElementById('reminderEnabled');
    
    if (form) {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            await saveUserPreferences();
        });
    }
    
    if (reminderEnabledCheckbox) {
        reminderEnabledCheckbox.addEventListener('change', toggleReminderTimeGroup);
    }
}

// 改进学习目标进度显示
async function loadLearningGoalsProgress() {
    try {
        const [goalsResponse, statsResponse] = await Promise.all([
            fetch('/api/user/learning-goals'),
            fetch('/api/user/stats')
        ]);
        
        const goalsData = await goalsResponse.json();
        const statsData = await statsResponse.json();

        if (goalsData.success && statsData.success) {
            displayGoalsWithProgress(goalsData.goals, statsData.stats);
        }
    } catch (error) {
        console.error('加载学习目标进度错误:', error);
    }
}

function displayGoalsWithProgress(goals, stats) {
    const dailyGoal = goals.find(g => g.goal_type === 'daily');
    const weeklyGoal = goals.find(g => g.goal_type === 'weekly');

    // 每日目标 - 使用今日答题数据
    const dailyItem = document.querySelector('.goal-item:nth-child(1)');
    if (dailyItem && dailyGoal) {
        const todayQuizzes = getTodayQuizCount(stats); // 需要从统计中获取今日数据
        const progress = Math.min((todayQuizzes / dailyGoal.target_quizzes) * 100, 100);
        dailyItem.querySelector('.goal-progress').textContent = `${todayQuizzes}/${dailyGoal.target_quizzes}`;
        dailyItem.querySelector('.progress-fill').style.width = `${progress}%`;
    }

    // 每周目标 - 使用本周答题数据
    const weeklyItem = document.querySelector('.goal-item:nth-child(2)');
    if (weeklyItem && weeklyGoal) {
        const weeklyQuizzes = getWeeklyQuizCount(stats); // 需要从统计中获取本周数据
        const progress = Math.min((weeklyQuizzes / weeklyGoal.target_quizzes) * 100, 100);
        weeklyItem.querySelector('.goal-progress').textContent = `${weeklyQuizzes}/${weeklyGoal.target_quizzes}`;
        weeklyItem.querySelector('.progress-fill').style.width = `${progress}%`;
    }
}

function getTodayQuizCount(stats) {
    // 这里应该从后端获取今日具体数据，暂时使用模拟数据
    return Math.floor(Math.random() * 10);
}

function getWeeklyQuizCount(stats) {
    // 这里应该从后端获取本周具体数据，暂时使用模拟数据
    return Math.floor(Math.random() * 50);
}

// 页面加载时执行
// 选项卡切换功能
function setupTabs() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const targetTab = btn.getAttribute('data-tab');
            
            // 移除所有按钮的激活状态
            tabBtns.forEach(b => b.classList.remove('active'));
            // 激活当前按钮
            btn.classList.add('active');
            
            // 隐藏所有面板
            tabPanes.forEach(pane => pane.classList.remove('active'));
            // 显示对应面板
            const targetPane = document.querySelector(`[data-tab-content="${targetTab}"]`);
            if (targetPane) {
                targetPane.classList.add('active');
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    loadUserInfo();
    loadQuizStats();
    loadQuizHistory();
    loadAchievements();
    loadLearningGoalsProgress(); // 使用改进的目标加载函数
    setupAvatarUpload();  // 初始化头像上传
    setupGoalModal();     // 初始化目标设置
    setupPreferencesForm(); // 初始化偏好设置表单
    setupTabs();          // 初始化选项卡
    setActiveNav();
});

// 添加fadeOut动画
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
`;
document.head.appendChild(style);

